<template>
  <div class="demo-page">
    <!-- 页面标题 -->
    <div class="demo-header">
      <h1>CrudImageUploader 组件演示</h1>
      <p class="demo-description">
        一个功能强大、高度可配置的图片上传组件，支持多种上传模式、文件验证、预览等功能。
      </p>
    </div>

    <!-- 演示区域 -->
    <div class="demo-content">
      <!-- 基础用法 -->
      <div class="demo-section">
        <h2>基础用法</h2>
        <p>最简单的使用方式，支持 PNG 格式，最大 2MB</p>
        <div class="demo-example">
          <CrudImageUploader v-model="basicImage" :validation-config="{
            allowedTypes: ['image/png'],
            maxSize: 2
          }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ basicImage || '未选择图片' }}
        </div>
      </div>

      <!-- 多格式支持 -->
      <div class="demo-section">
        <h2>多格式支持</h2>
        <p>支持多种图片格式：PNG、JPEG、GIF、WebP</p>
        <div class="demo-example">
          <CrudImageUploader v-model="multiFormatImage" :validation-config="{
            allowedTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
            maxSize: 5
          }" :preview-config="{
              width: 120,
              height: 120,
              borderRadius: '8px'
            }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ multiFormatImage || '未选择图片' }}
        </div>
      </div>

      <!-- 即时上传模式 -->
      <div class="demo-section">
        <h2>即时上传模式</h2>
        <p>选择文件后立即上传到服务器</p>
        <div class="demo-example">
          <CrudImageUploader v-model="immediateImage" upload-mode="immediate" :validation-config="{
            allowedTypes: ['image/png', 'image/jpeg'],
            maxSize: 3
          }" :upload-config="{
              action: '/api/upload/immediate',
              name: 'file',
              data: { type: 'immediate' }
            }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ immediateImage || '未选择图片' }}
        </div>
      </div>

      <!-- 延迟上传模式 -->
      <div class="demo-section">
        <h2>延迟上传模式</h2>
        <p>选择文件后暂存，需要手动调用上传方法</p>
        <div class="demo-example">
          <CrudImageUploader ref="deferredUploaderRef" v-model="deferredImage" upload-mode="deferred"
            :validation-config="{
              allowedTypes: ['image/png', 'image/jpeg'],
              maxSize: 3
            }" :upload-config="{
              action: '/api/upload/deferred',
              name: 'file',
              data: { type: 'deferred' }
            }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError"
            @file-change="handleFileChange" />
          <div class="demo-actions" v-if="hasPendingFile">
            <el-button type="primary" @click="uploadDeferredFile" :loading="uploading">
              手动上传
            </el-button>
            <el-button @click="clearDeferredFile">
              清除文件
            </el-button>
          </div>
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ deferredImage || '未选择图片' }}
        </div>
      </div>

      <!-- 自定义预览样式 -->
      <div class="demo-section">
        <h2>自定义预览样式</h2>
        <p>可以自定义预览图片的尺寸、边框等样式</p>
        <div class="demo-example">
          <div class="custom-preview-grid">
            <!-- 圆形头像 -->
            <div class="preview-item">
              <h4>圆形头像</h4>
              <CrudImageUploader v-model="avatarImage" :validation-config="{
                allowedTypes: ['image/png', 'image/jpeg'],
                maxSize: 2
              }" :preview-config="{
                  width: 80,
                  height: 80,
                  borderRadius: '50%'
                }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
            </div>

            <!-- 方形缩略图 -->
            <div class="preview-item">
              <h4>方形缩略图</h4>
              <CrudImageUploader v-model="thumbnailImage" :validation-config="{
                allowedTypes: ['image/png', 'image/jpeg'],
                maxSize: 2
              }" :preview-config="{
                  width: 100,
                  height: 100,
                  borderRadius: '4px'
                }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
            </div>

            <!-- 横向横幅 -->
            <div class="preview-item">
              <h4>横向横幅</h4>
              <CrudImageUploader v-model="bannerImage" :validation-config="{
                allowedTypes: ['image/png', 'image/jpeg'],
                maxSize: 2
              }" :preview-config="{
                  width: 200,
                  height: 80,
                  borderRadius: '8px'
                }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
            </div>
          </div>
        </div>
      </div>

      <!-- 禁用状态 -->
      <div class="demo-section">
        <h2>禁用状态</h2>
        <p>组件可以设置为禁用状态</p>
        <div class="demo-example">
          <div class="disabled-controls">
            <el-switch v-model="isDisabled" active-text="禁用" inactive-text="启用" />
          </div>
          <CrudImageUploader v-model="disabledImage" :disabled="isDisabled" :validation-config="{
            allowedTypes: ['image/png', 'image/jpeg'],
            maxSize: 2
          }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ disabledImage || '未选择图片' }}
        </div>
      </div>

      <!-- 只读状态 -->
      <div class="demo-section">
        <h2>只读状态</h2>
        <p>组件可以设置为只读状态，只能查看不能修改</p>
        <div class="demo-example">
          <div class="readonly-controls">
            <el-switch v-model="isReadonly" active-text="只读" inactive-text="可编辑" />
          </div>
          <CrudImageUploader v-model="readonlyImage" :readonly="isReadonly" :validation-config="{
            allowedTypes: ['image/png', 'image/jpeg'],
            maxSize: 2
          }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ readonlyImage || '未选择图片' }}
        </div>
      </div>

      <!-- 配置面板 -->
      <div class="demo-section">
        <h2>交互式配置</h2>
        <p>实时调整组件配置，查看效果</p>
        <div class="config-panel">
          <div class="config-form">
            <el-form label-width="120px" size="small">
              <el-form-item label="上传模式">
                <el-radio-group v-model="configUploadMode">
                  <el-radio value="immediate">即时上传</el-radio>
                  <el-radio value="deferred">延迟上传</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="允许格式">
                <el-checkbox-group v-model="configAllowedTypes">
                  <el-checkbox value="image/png">PNG</el-checkbox>
                  <el-checkbox value="image/jpeg">JPEG</el-checkbox>
                  <el-checkbox value="image/gif">GIF</el-checkbox>
                  <el-checkbox value="image/webp">WebP</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="最大大小(MB)">
                <el-input-number v-model="configMaxSize" :min="1" :max="10" />
              </el-form-item>

              <el-form-item label="预览宽度">
                <el-input-number v-model="configPreviewWidth" :min="50" :max="300" />
              </el-form-item>

              <el-form-item label="预览高度">
                <el-input-number v-model="configPreviewHeight" :min="50" :max="300" />
              </el-form-item>

              <el-form-item label="圆角大小">
                <el-input v-model="configBorderRadius" placeholder="如: 8px, 50%" />
              </el-form-item>
            </el-form>
          </div>

          <div class="config-preview">
            <CrudImageUploader v-model="configImage" :upload-mode="configUploadMode" :validation-config="{
              allowedTypes: configAllowedTypes,
              maxSize: configMaxSize
            }" :preview-config="{
                width: configPreviewWidth,
                height: configPreviewHeight,
                borderRadius: configBorderRadius
              }" :upload-config="{
                action: '/api/upload/config',
                name: 'file'
              }" @upload-success="handleUploadSuccess" @upload-error="handleUploadError" />
          </div>
        </div>
        <div class="demo-result">
          <strong>当前值：</strong>{{ configImage || '未选择图片' }}
        </div>
      </div>

      <!-- 代码示例 -->
      <div class="demo-section">
        <h2>代码示例</h2>
        <div class="code-examples">
          <el-tabs v-model="activeCodeTab">
            <el-tab-pane label="基础用法" name="basic">
              <pre class="code-block"><code>&lt;CrudImageUploader
  v-model="imageUrl"
  :validation-config="{
    allowedTypes: ['image/png'],
    maxSize: 2
  }"
  @upload-success="handleUploadSuccess"
  @upload-error="handleUploadError"
/&gt;</code></pre>
            </el-tab-pane>

            <el-tab-pane label="即时上传" name="immediate">
              <pre class="code-block"><code>&lt;CrudImageUploader
  v-model="imageUrl"
  upload-mode="immediate"
  :validation-config="{
    allowedTypes: ['image/png', 'image/jpeg'],
    maxSize: 3
  }"
  :upload-config="{
    action: '/api/upload',
    name: 'file',
    data: { type: 'immediate' }
  }"
  @upload-success="handleUploadSuccess"
  @upload-error="handleUploadError"
/&gt;</code></pre>
            </el-tab-pane>

            <el-tab-pane label="自定义预览" name="preview">
              <pre class="code-block"><code>&lt;CrudImageUploader
  v-model="imageUrl"
  :validation-config="{
    allowedTypes: ['image/png', 'image/jpeg'],
    maxSize: 2
  }"
  :preview-config="{
    width: 120,
    height: 120,
    borderRadius: '8px'
  }"
  @upload-success="handleUploadSuccess"
  @upload-error="handleUploadError"
/&gt;</code></pre>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 页面标题
 */
defineOptions({
  name: 'CrudImageUploaderDemo'
})

// 基础示例
const basicImage = ref('')

// 多格式示例
const multiFormatImage = ref('')

// 即时上传示例
const immediateImage = ref('')

// 延迟上传示例
const deferredImage = ref('')
const deferredUploaderRef = ref()
const hasPendingFile = ref(false)
const uploading = ref(false)

// 自定义预览示例
const avatarImage = ref('')
const thumbnailImage = ref('')
const bannerImage = ref('')

// 禁用状态示例
const disabledImage = ref('')
const isDisabled = ref(false)

// 只读状态示例
const readonlyImage = ref('https://via.placeholder.com/150x150/4CAF50/FFFFFF?text=ReadOnly')
const isReadonly = ref(true)

// 配置面板
const configImage = ref('')
const configUploadMode = ref<'immediate' | 'deferred'>('immediate')
const configAllowedTypes = ref(['image/png', 'image/jpeg'])
const configMaxSize = ref(2)
const configPreviewWidth = ref(100)
const configPreviewHeight = ref(100)
const configBorderRadius = ref('8px')

// 代码示例
const activeCodeTab = ref('basic')

/**
 * 处理上传成功
 * @param result - 上传结果
 */
const handleUploadSuccess = (result: Record<string, unknown>): void => {
  ElMessage.success('图片上传成功！')
  console.log('上传成功:', result)
}

/**
 * 处理上传错误
 * @param error - 错误信息
 */
const handleUploadError = (error: string): void => {
  ElMessage.error(`上传失败: ${error}`)
  console.error('上传失败:', error)
}

/**
 * 处理文件选择变化
 * @param file - 选择的文件
 */
const handleFileChange = (file: File | null): void => {
  hasPendingFile.value = !!file
}

/**
 * 手动上传延迟文件
 */
const uploadDeferredFile = async (): Promise<void> => {
  if (!deferredUploaderRef.value) return

  try {
    uploading.value = true
    await deferredUploaderRef.value.uploadFile()
    hasPendingFile.value = false
    ElMessage.success('延迟上传完成！')
  } catch {
    ElMessage.error('延迟上传失败！')
  } finally {
    uploading.value = false
  }
}

/**
 * 清除延迟文件
 */
const clearDeferredFile = (): void => {
  if (deferredUploaderRef.value) {
    deferredUploaderRef.value.clearFile()
    hasPendingFile.value = false
    ElMessage.info('已清除待上传文件')
  }
}
</script>

<style scoped lang="scss">
.demo-page {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f5f5f5;
  min-height: 100vh;
}

.demo-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 32px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  h1 {
    font-size: 32px;
    color: #2c3e50;
    margin-bottom: 16px;
    font-weight: 600;
  }

  .demo-description {
    font-size: 16px;
    color: #7f8c8d;
    line-height: 1.6;
    max-width: 600px;
    margin: 0 auto;
  }
}

.demo-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.demo-section {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  h2 {
    font-size: 24px;
    color: #2c3e50;
    margin-bottom: 8px;
    font-weight: 600;
  }

  p {
    color: #7f8c8d;
    margin-bottom: 24px;
    line-height: 1.6;
  }
}

.demo-example {
  margin-bottom: 20px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.demo-result {
  padding: 16px;
  background: #e8f5e8;
  border-radius: 6px;
  border-left: 4px solid #4caf50;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 14px;
  color: #2e7d32;
}

.demo-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
}

.custom-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
}

.preview-item {
  text-align: center;

  h4 {
    margin-bottom: 16px;
    color: #495057;
    font-weight: 500;
  }
}

.disabled-controls,
.readonly-controls {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff3cd;
  border-radius: 6px;
  border: 1px solid #ffeaa7;
}

.config-panel {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 32px;
  align-items: start;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.config-form {
  background: #f8f9fa;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.config-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.code-examples {
  .code-block {
    background: #2d3748;
    color: #e2e8f0;
    padding: 20px;
    border-radius: 8px;
    overflow-x: auto;
    font-family: 'Monaco', 'Menlo', monospace;
    font-size: 14px;
    line-height: 1.5;
    margin: 0;

    code {
      background: none;
      color: inherit;
      padding: 0;
      font-size: inherit;
    }
  }
}

:deep(.el-tabs__content) {
  padding-top: 16px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}
</style>
